package com.xmg.unsafe;

import lombok.Data;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnsafeDemo {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        Unsafe unsafe = (Unsafe)theUnsafe.get(null);

        System.out.println(unsafe);

        long id = unsafe.objectFieldOffset(User.class.getDeclaredField("id"));
        long name = unsafe.objectFieldOffset(User.class.getDeclaredField("name"));
        User user = new User();

        Field name1 = user.getClass().getDeclaredField("name");
        name1.setAccessible(true);
        name1.set(user,"王五");

        unsafe.compareAndSwapInt(user,id,0,123);
        unsafe.compareAndSwapObject(user,name,null,"大神");

        System.out.println(user);
    }
}

@Data
class User{
    int id;
    String name;
}
